package com.sdjz.club.club.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sdjz.club.club.common.Result;
import com.sdjz.club.club.entity.WxUserInfo;
import com.sdjz.club.club.mapper.WxuserinfoMapper;
import com.sdjz.club.club.service.WxuserinfoService;
import com.sdjz.club.club.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service("wxUserInfoService")
public class WxuserinfoServiceImp extends ServiceImpl<WxuserinfoMapper, WxUserInfo> implements WxuserinfoService {
    //定死 不需要修改
    private static final String jscode2sessionUrl = "https://api.weixin.qq.com/sns/jscode2session";
    private static final String appid = "wxc35a3e60cc6c3cfc";    //todo 必改 改成自己的appid
    private static final String secret = "64f19d50b5f9ab9332430c1b83403e77";//todo 必改 改成自己的密钥
    @Autowired
    private WxuserinfoMapper wxUserInfoMapper;
    @Autowired
    private HttpClientUtil httpClientUtil;

    //实现登陆的逻辑
    @Override
    public Result Login(WxUserInfo wxUserInfo) {
        String getMessageUrl = jscode2sessionUrl +
                "?appid=" + appid + "&secret=" +
                secret + "&js_code=" +
                wxUserInfo.getCode() +
                "&grant_type=authorization_code";
        String result = httpClientUtil.sendHttpGet(getMessageUrl);
        JSONObject jsonObject = JSON.parseObject(result);
        String openid = jsonObject.get("openid").toString();

        // todo 至此我们已经获取到openID
        // todo 下面书写自己的业务逻辑 随意发挥

        // todo 这个是我的业务逻辑 可以参考（较简单）
        QueryWrapper<WxUserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("openid", openid);
        WxUserInfo user = wxUserInfoMapper.selectOne(wrapper);
        if (user == null) {
            System.out.println("插入用户");
            try {
                wxUserInfo.setOpenid(openid);
            } catch (Exception e) {
                e.printStackTrace();
            }
            wxUserInfo.setRegisterDate(new Date());
            wxUserInfo.setLastLoginDate(new Date());
            wxUserInfoMapper.insert(wxUserInfo);
        } else {
            System.out.println("更新用户");
            user.setNickName(wxUserInfo.getNickName());
            user.setAvatarUrl(wxUserInfo.getAvatarUrl());
            user.setLastLoginDate(new Date());
            wxUserInfoMapper.updateById(user);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("data", user);
        return Result.succ(map);
    }
}
